package com.mg.sms;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.ProgressDialog;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.mg.sms.dao.DBHelper;
import com.mg.sms.dao.SMSConstant;

/**
 * <p>Title: com.mg.sms.BearSMS</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2011</p>
 * <p>Company: FreeLance</p>
 * @author Jason Huang
 * @version 1.0
 */
public class BearSMS extends Activity {
	    
    private static final String _account = "mg622000@gmail.com";
    
    private static final String _password = "q19791129";
    
    private static final int CONTEXT_MENU_SEND = 0;
    
    private static final int CONTEXT_MENU_DELETE = 1;
    
    private static final int CONTEXT_MENU_CANCEL = 2;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
//        Intent messageService = new Intent(this, MessageService.class);
//        messageService.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        startService(messageService);
        Log.i("bear", "iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii");
//        MessageTask task = new MessageTask(this);
//        task.execute();
//        TextView tx = (TextView)findViewById(R.id.output);
//        task.execute(tx);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(getString(R.string.menu_btn_reload)).setIcon(android.R.drawable.ic_menu_rotate).setOnMenuItemClickListener(new ReloadItemClickListener());
        menu.add(getString(R.string.menu_btn_exit)).setIcon(android.R.drawable.ic_menu_close_clear_cancel).setOnMenuItemClickListener(new ExitMenuItemClickListener());
        return super.onCreateOptionsMenu(menu);
    }
    
    @Override  
    public boolean onContextItemSelected(MenuItem item) {   
        return super.onContextItemSelected(item);  
    }  
    

    /**
     * <p>Title: com.mg.sms.ExitMenuItemClickListener</p>
     * <p>Description: 離開</p>
     * <p>Copyright: Copyright (c) 2011</p>
     * <p>Company: FreeLance</p>
     * @author Jason Huang
     * @version 1.0
     */
    private class ExitMenuItemClickListener implements OnMenuItemClickListener {
        @Override
        public boolean onMenuItemClick(MenuItem arg0) {
            finish();
            return false;
        }
    }
    
    /**
     * <p>Title: com.mg.sms.ReloadItemClickListener</p>
     * <p>Description: 重新整理</p>
     * <p>Copyright: Copyright (c) 2011</p>
     * <p>Company: FreeLance</p>
     * @author Jason Huang
     * @version 1.0
     */
    private class ReloadItemClickListener implements OnMenuItemClickListener {

        @Override
        public boolean onMenuItemClick(MenuItem arg0) {
            ListView listView = (ListView)findViewById(R.id.smsList);
            ProgressDialog dialog = ProgressDialog.show(BearSMS.this, "", getString(R.string.msg_reload), true);
            MessageTask messageTask = new MessageTask(BearSMS.this, listView, dialog);
            messageTask.execute(new String[]{_account, _password});
            return false;
        }
    }
    
    /**
     * <p>Title: com.mg.sms.MessageTask</p>
     * <p>Description: 背景下載信件</p>
     * <p>Copyright: Copyright (c) 2011</p>
     * <p>Company: FreeLance</p>
     * @author Jason Huang
     * @version 1.0
     */
    private class MessageTask extends AsyncTask<String, Integer, List<Map<String, Object>>> {
        
        private final Activity activity;
        
        private final ProgressDialog dialog;
        
        private final ListView listView;
        
        private Handler handler = new Handler();
        
        public MessageTask(Activity activity, ListView listView, ProgressDialog dialog) {
            this.activity = activity;
            this.listView = listView;
            this.dialog = dialog;
        }
        
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected List<Map<String, Object>> doInBackground(String... arg) {
            try {
                GmailManager.mailSyncToDB(activity, arg[0], arg[1]);
                return query(activity);
            } catch(Exception ex) {
                Log.d("bear", ex.getMessage(), ex);
            }
            return null;
        }
        
        @Override
        protected void onPostExecute(final List<Map<String, Object>> result) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    dialog.cancel();
                    if(result != null) {                        
                        SimpleAdapter simpleAdapter = new SimpleAdapter(activity, result, R.layout.row, new String[]{SMSConstant.SMS_STATUS, SMSConstant.SMS_TEL, SMSConstant.SMS_FROM, SMSConstant.SMS_BODY}, new int[]{R.id.status, R.id.tel, R.id.from, R.id.body});
                        listView.setAdapter(simpleAdapter);
                        listView.setOnCreateContextMenuListener(new ListViewOnCreateContextMenuListener());
                        // listView.setOnItemClickListener(new ListViewOnClickListener());
                    }
                }
            });
        }
        
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
        }
        
        @Override
        protected void onCancelled() {
            super.onCancelled();
        }
        
        /**
         * 查詢資料
         * @param activity
         * @return
         * @throws Exception
         */
        private List<Map<String, Object>> query(Activity activity) throws Exception{
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh24:mm:ss");
            
            // 取得DB資料
            DBHelper dbHelper = new DBHelper(activity);
            SQLiteDatabase sqliteDatabase = dbHelper.getReadableDatabase();
            Cursor cursor = sqliteDatabase.rawQuery("SELECT * FROM SMS ORDER BY SMS_RECEIVED_DATE DESC", null);
            
            // 建立資料
            List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
            for(cursor.moveToFirst(); ! cursor.isAfterLast(); cursor.moveToNext()){ 
                Map<String, Object> map = new HashMap<String, Object>();
                String id           = cursor.getString(cursor.getColumnIndex(SMSConstant.SMS_ID));
                String tel          = cursor.getString(cursor.getColumnIndex(SMSConstant.SMS_TEL));
                String from         = cursor.getString(cursor.getColumnIndex(SMSConstant.SMS_FROM));
                String body         = cursor.getString(cursor.getColumnIndex(SMSConstant.SMS_BODY));
                String status       = cursor.getString(cursor.getColumnIndex(SMSConstant.SMS_STATUS));
                String receivedDate = cursor.getString(cursor.getColumnIndex(SMSConstant.SMS_RECEIVED_DATE));
                
                int icon = 0;
                if(SMSConstant.STATUS_INCOMPLETE.equals(status)) icon = R.drawable.orange;
                if(SMSConstant.STATUS_COMPLETE.equals(status)) icon = R.drawable.green;
                if(SMSConstant.STATUS_FAIL.equals(status)) icon = R.drawable.red;
                
                Log.i("bear", "id:" + id);
                Log.i("bear", "tel:" + tel);
                Log.i("bear", "from:" + from);
                Log.i("bear", "status:" + status);
                Log.i("bear", "body:" + body);
                Log.i("bear", "receivedDate" + sf.format(new Date(Long.valueOf(receivedDate))));
                Log.i("bear", "-------------------------------------------------");
                
                map.put(SMSConstant.SMS_ID,             id);
                map.put(SMSConstant.SMS_TEL,            tel);
                map.put(SMSConstant.SMS_FROM,           from);
                map.put(SMSConstant.SMS_STATUS,         icon);
                map.put(SMSConstant.SMS_BODY,           body);
                map.put(SMSConstant.SMS_RECEIVED_DATE,  sf.format(new Date(Long.valueOf(receivedDate))));
                
                data.add(map);
            } 
            return data;
        }
    }
    
    /**
     * <p>Title: com.mg.sms.ListViewOnCreateContextMenuListener</p>
     * <p>Description: ListView長按選單</p>
     * <p>Copyright: Copyright (c) 2011</p>
     * <p>Company: FreeLance</p>
     * @author Jason Huang
     * @version 1.0
     */
    private class ListViewOnCreateContextMenuListener implements OnCreateContextMenuListener {

        @Override
        public void onCreateContextMenu(ContextMenu menu, View arg1, ContextMenuInfo arg2) {
            menu.setHeaderTitle(R.string.context_menu);     
            menu.add( 0, CONTEXT_MENU_SEND,     1, R.string.context_menu_send);  
            menu.add( 0, CONTEXT_MENU_DELETE ,  2, R.string.context_menu_delete);
            menu.add( 0, CONTEXT_MENU_CANCEL ,  3, R.string.context_menu_cancel);
        }
        
    }
}